// 导航条点击滚动
define(['backbone', './scrollTo'], function(Backbone) {
	var navScrollView = Backbone.View.extend({
		el: '#app',
		initialize: function() {
			this.renderEls();
			this.bindEvents();
			this.evt_fixNav();
		},
		events: {
			'click .scroll-nav a:not(.is-cur)': 'evt_scrollToDom'
		},
		renderEls: function() {
			this.els = {
				header: this.$('.com-header'),
				navBar: this.$('.scroll-nav'),
				navs: this.$('.scroll-nav a'),
				targetDoms: this.$('[data-scroll]')
			}
		},
		bindEvents: function() {
			$(window).off('scroll.fixNav').on('scroll.fixNav', _.bind(this.evt_fixNav, this));
			this.targetTop = this.els.navBar.height() + this.els.navBar.offset().top;
		},
		evt_fixNav: function() {
			var _page = this;
			var scrollTop = $(window).scrollTop();
			if (scrollTop >= this.targetTop) {
				this.els.navBar
					.addClass('is-fixed')
					.css({top: this.els.header.height() - 1});
				this.els.header.css('border-bottom', 'none');
			} else {
				this.els.navBar
					.removeClass('is-fixed')
					.css({top: 0});
			}

			this.els.targetDoms.each(function(idx, ele) {
				var $dom = $(this);
				var targetId = $dom.data('scroll');
				var headerH = _page.els.header.height() + _page.els.navBar.height();
				var boundSt = $dom.offset().top - headerH;
				var boundSE = boundSt + $dom.height();
				var $targetDOM;
				if (scrollTop >= boundSt && scrollTop <= boundSE) {
					$targetDOM = _page.$('[data-target="'+targetId+'"]');
					if ($targetDOM && $targetDOM.length) {
						_page.els.navs.removeClass('is-cur');
						$targetDOM.addClass('is-cur');
					}
				}
			});
		},
		evt_scrollToDom: function(e) {
			var _page = this;
			var $target = $(e.currentTarget);
			var targetId = $target.data('target');
			var headerH = this.els.header.height() + this.els.navBar.height();
			var $targetDOM;
			var targetTop = 0;
			if (targetId) {
				$targetDOM = this.$('[data-scroll="'+targetId+'"]');
				this.els.navs.removeClass('is-cur');
				$target.addClass('is-cur');
			}
			if ($targetDOM.length) {
				targetTop = $targetDOM.eq(0).offset().top - headerH;
				// 点击的时候需要操作window的scroll，为了避免事件冲突，需要off一下
				// 滚动结束后再回调打开事件监听
				$(window).off('scroll.fixNav');
				$(window).scrollTo({
					toT: targetTop,
					durTime: Math.min(targetTop / 4, 300),
					callback: function() {
						$(window).off('scroll.fixNav').on('scroll.fixNav', _.bind(_page.evt_fixNav, _page));
					}
				});
			}
		}
	});
	return navScrollView;
});